'''
Created on Mar 20, 2013

@author: jason.richmond
'''
from SimPy.Simulation import *
from Globals import *

class Machine(Process):
    SrvRate = None #reciprocal of mean service time
    Busy = [] #busy machine
    Idle = [] #idle machines
    PriorityQueue = [] #priority job queue
    Queue = [] #best effort queue
    NDone = 0 #jobs completed
    TotWait = 0.0 #total wait time for all jobs (includes queue and service)
    
    def __init__(self):
        Process.__init__(self)
        Machine.Idle.append(self)
        
    def Run(self):
        while 1:
            #sleep until machine awakened
            yield passivate,self
            Machine.Idle.remove(self)
            Machine.Busy.append(self)
            
            #If the queue is not empty take a job
            while Machine.Queue != []:
                #get a job
                J = Machine.Queue.pop(0)
                #process the job
                #a random amount of time will pass and the job will be processed.
                yield hold,self,G.Rnd.expovariate(Machine.SrvRate)
                #bookkeeping
                Machine.NDone += 1
                Machine.TotWait += now() - J.ArrivalTime
            
            Machine.Busy.remove(self)
            Machine.Idle.append(self)
    